<template>
  <div class="page-container-padding">
    <div style="display: flex">
      <el-button icon="el-icon-plus" type="primary" @click="toShowEditDialog">
        添加
      </el-button>
      <!-- 检索框-->
      <el-select
        v-model="queryParam.v"
        filterable
        clearable
        style="margin-right: 5px; margin-left: 6px"
        placeholder="全部品种"
      >
        <el-option
          v-for="(v, i) in varietyList"
          :key="i"
          :value="v.variety_en"
          :label="v.variety_long_name"
        ></el-option>
      </el-select>
      <el-input
        v-model="queryParam.kw"
        placeholder="请输入内容"
        clearable
        style="margin-left: 6px;"
        @change="getEconomyDataSheet"
      >
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="getEconomyDataSheet"
        ></el-button>
      </el-input>
    </div>
    <!-- 显示数据量 -->
    <div class="count-box">
      <div v-for="item in groupCountData" :key="item.prop" class="count-item">
        {{ item.name }}: {{ item.count }} ({{ (item.rate * 100).toFixed(2) }}%)
      </div>
    </div>
    <div style="margin-top: 5px">
      <el-table border row-class-name='table-row' :data='tableList'>
        <el-table-column type="expand" label="详细" width='50'>
          <template slot-scope="props">
            <div style="margin-left:48px;">
              <el-form label-position="left" class="table-expand-form">
                <el-form-item label="平台ID"><span>{{ props.row.source_id }}</span></el-form-item>
                <el-form-item label="数据平台"><span>{{ props.row.source_plat }}</span></el-form-item>
                <el-form-item label="来源"><span>{{ props.row.raw_source }}</span></el-form-item>
                <el-form-item label="三方数据"><span>{{  props.row.three_plat }}</span></el-form-item>
                <el-form-item label="状态"><span>{{ props.row.state_text }}</span></el-form-item>
                <el-form-item label="归类品种">
                  <el-input v-model="props.row.variety" placeholder="填入品种交易代码" size="mini" style="width:200px;margin-right:8px;"></el-input>
                  <el-button type="text" @click="toClassifyIndex(props.row)">保存</el-button>
                </el-form-item>
                <el-form-item label="操作"><span><i class="el-icon-delete-solid" style="color:#F34D37;cursor:pointer;" @click="toDeleteEDBTable(props.row)"></i></span></el-form-item>
              </el-form>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="ID" prop="id" width="70px"></el-table-column>
        <el-table-column label="指标名称" prop="name_zh" show-overflow-tooltip>
          <template slot-scope="scope">
            <div class="namerow">
              <span class="namezh">{{ scope.row.name_zh }}</span>
              <span class="rowactions" @click="toBrushIndexData(scope.row)">
                <vab-icon :icon="['fas', 'brush']" class="brush"></vab-icon>
              </span>
              <span class="rowactions" @click="toPopIndexData(scope.row)">
                <vab-icon :icon="['fas', 'eye']"></vab-icon>
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="频率" prop="frequency" width='50px' show-overflow-tooltip></el-table-column>
        <el-table-column label="源" prop="source_plat" width='50px' show-overflow-tooltip></el-table-column>
        <el-table-column label="源ID" prop="source_id" width="110px" show-overflow-tooltip></el-table-column>
        <el-table-column label="指标单位" prop="unit" width="90px" show-overflow-tooltip></el-table-column>
        <el-table-column label="起始日期" prop="startdate" width="100px"></el-table-column>
        <el-table-column label="结束日期" prop="enddate" width="100px"></el-table-column>
        <el-table-column label="创建时间" prop="create_time" width="140px"></el-table-column>
        <el-table-column label="更新时间" prop="refresh" width="140px"></el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 5px"
        background
        :current-page="queryParam.page"
        :page-size="queryParam.page_size"
        layout="total, prev, pager, next, jumper"
        :total="totalTableCount"
        @current-change="currentPageChanged"
      ></el-pagination>
    </div>

    <!-- 新建表弹窗 -->
    <el-dialog :visible.sync="showEditDialog" title="新建数据表">
      <el-form label-width="80px" :model="editTableObj">
        <el-form-item label="数据平台">
          <el-select v-model="editTableObj.source_plat" @change="checkIndexExists">
            <el-option v-for="item in sourcePlatList" :label="item.label" :value="item.value" :key="item.value"></el-option>
          </el-select>
          <span v-show="indexIsExists" style="margin-left:10px;color:#FF0000;">该数据ID已存在！！！</span>
        </el-form-item>
        <el-form-item label="平台ID">
          <el-input v-model.trim="editTableObj.source_id" @blur="checkIndexExists" type="text" placeholder="输入平台的指标ID"></el-input>
        </el-form-item>
        <el-form-item label="指标名称">
          <el-input v-model.trim="editTableObj.name_zh" type="text" placeholder="输入平台的指标名称"></el-input>
        </el-form-item>
        <el-form-item label="频率">
          <el-select v-model="editTableObj.frequency">
            <el-option v-for="item in frequencyList" :label="item.label" :value="item.value" :key="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="指标单位">
          <el-input v-model.trim="editTableObj.unit" placeholder="输入平台的数据指标单位"></el-input>
        </el-form-item>
        <el-form-item label="数据来源">
          <el-input v-model.trim="editTableObj.raw_source" placeholder="输入平台的数据来源"></el-input>
        </el-form-item>
        <el-form-item label="起始时间">
          <el-date-picker v-model="editTableObj.startdate" placeholder="输入数据起始日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="归属品种">
          <el-input v-model.trim="editTableObj.variety" placeholder="品种的交易所代码,用逗号隔开"></el-input>
        </el-form-item>
        <el-form-item label="三方数据">
          <el-input
            v-model.trim="editTableObj.three_plat"
            placeholder="三方数据名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model.trim="editTableObj.note" placeholder="数据备注"></el-input>
        </el-form-item>
        <el-form-item label="更新状态">
          <el-radio v-model="editTableObj.state" :label="1">正常</el-radio>
          <el-radio v-model="editTableObj.state" :label="0">停止更新</el-radio>
        </el-form-item>
        <el-form-item label="对外开放">
          <el-radio v-model="editTableObj.is_open" :label="1">开放</el-radio>
          <el-radio v-model="editTableObj.is_open" :label="0">隐藏</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="showEditDialog=false">取消</el-button>
        <el-button type="primary" @click="confirmAddTable" :disabled="indexIsExists">确定</el-button>
      </div>
    </el-dialog>
  
    <!-- 指标数据详情弹窗 -->
    <IndexDetaiPopup :indexId="currentDetailId" :show="showIndexDetail" :title="detailDialogTitle"></IndexDetaiPopup>

  </div>
</template>

<script>
  let NAME_SPACE = 'V03'
  import IndexDetaiPopup from '@/components/DataIndex'
  import { datetimeToStr } from '@/utils/datetimeUtils'
  import { getUserAuthVariety } from '@/api/operations/variety'
  import {
    getEDBTables,
    addEDBTable,
    deleteEDBTable,
    getEDBIndexExists,
    classifyIndex,
    getIndexGrouper,
    brushEDBTable,
  } from '@/api/edbdata/datalib'
  export default {
    components: {
      IndexDetaiPopup,
    },
    data() {
      return {
        showEditDialog: false,
        sourcePlatList: [{label: 'Wind数据库', value: 'wind'}, {label: 'THS数据库', value: 'ths'}],
        frequencyList: [{label: '年', value: '年'},  {label: '季', value: '季'}, {label: '月', value: '月'}, {label: '周', value: '周'}, {label: '日', value: '日'}],
        editTableObj:{},
        indexIsExists: false,
        varietyList: [],

        tableList:[],
        totalTableCount: 1,
        queryParam: {
          kw: '',
          v: '',
          page: 1,
          page_size: 50
        },
        refreshLoading: false,

        groupCountData: [],

        // 数据详情组件
        detailDialogTitle: '数据详情',
        currentDetailId: -1,
        showIndexDetail: false,
      }
    },
    mounted() {
      getUserAuthVariety({ space: NAME_SPACE }).then((res) => {
        this.varietyList = res.data
      })
      this.getEconomyDataSheet()
      // 获取各组指标数量及其占比
      getIndexGrouper().then((res) => {
        this.groupCountData = res.data
      })
    },
    methods: {
      initEditObj() {
        this.editTableObj = {
          source_plat: '',
          source_id: '',
          name_zh: '',
          frequency: '',
          unit: '',
          raw_source: '',
          startdate: null,
          three_plat: '',
          note: '',
          state: 1,
          is_open: 1,
          variety: '',
        }
      },
      toShowEditDialog(){
        this.initEditObj()
        this.showEditDialog = true
      },

      // 分类
      toClassifyIndex(row){
        const classifyData = {
          dataid: row.id,
          variety: row.variety
        }
        classifyIndex(classifyData).then(res => {
          this.$baseMessage(res.msg, 'success')
        })
      },

      // 删除一个指标数据
      toDeleteEDBTable(row){
        const delData = {
          indexid: row.id
        }
        this.$baseConfirm('确定删除这个数据指标吗?',null, ()=> {
          deleteEDBTable(delData).then(res => {
            if (res.code === 200){
              this.$baseMessage(res.msg, 'success')
              this.getEconomyDataSheet()
            }else{
              this.$baseMessage(res.msg, 'error')
            }
          })
        })
      },

      // 查询当前录入指标是否已存在
      checkIndexExists(){
        if (!this.editTableObj.source_plat)return
        if (!this.editTableObj.source_id)return
        const params = {
          plat: this.editTableObj.source_plat,
          sid: this.editTableObj.source_id
        }
        getEDBIndexExists(params).then(res => {
          if (res.data.id) {
            this.indexIsExists = true
          } else {
            this.indexIsExists = false
          }
        })
      },

      // 确定添加一个数据指标
      confirmAddTable() {
        this.editTableObj.startdate = datetimeToStr(
          this.editTableObj.startdate,
          true,
          '-'
        )
        console.log(this.editTableObj);
        addEDBTable(this.editTableObj).then((res) => {
          this.$baseMessage(res.msg, 'success')
          this.showEditDialog = false
          this.initEditObj()
        })
      },

      currentPageChanged(page){
        this.queryParam.page = page
        this.getEconomyDataSheet()
      },

      getEconomyDataSheet() {
        getEDBTables(this.queryParam).then((res) => {
          const data = res.data
          this.tableList = data.records
          this.totalTableCount = data.total_count
          this.queryParam.page = data.current_page
        })
      },

      // 点击了表格行(弃用,封装了弹窗操作组件)
      // indexTableRowClick(row, column, event){
      //   if (column.property !== 'name_zh') return
      //   this.$router.push({name:'DataRecRDBIndexDetail', query: {iid: row.id}})
      // },

      // 点击弹窗显示数据,并支持修改,改变值,弹窗组件即可
      toPopIndexData(row) {
        this.showIndexDetail = true
        this.currentDetailId = row.id
        this.detailDialogTitle = row.name_zh
      },

      // 清除数据
      toBrushIndexData(row) {
        const tipMsg = `清空【${row.name_zh}】\n并重新设置一个起始日期?\n(yyyy-mm-dd)`
        this.$prompt(tipMsg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        })
          .then(({ value }) => {
            const startDate = value ? value.trim() : ''
            const brushData = {
              index_id: row.id,
              start_date: startDate ? startDate : '',
            }
            brushEDBTable(brushData).then((res) => {
              if (res.code === 200) {
                this.$baseMessage(res.msg, 'success')
                this.getEconomyDataSheet()
              } else {
                this.$baseMessage(res.msg, 'error')
              }
            })
          })
          .catch(() => {})
      },
    },
  }
</script>

<style socped lang="scss">
  .count-box {
    margin-top: 6px;
    background-color: #5f9ea0;
    color: #f5f7fa;
    padding: 5px 10px;
    display: flex;
    text-align: center;
    align-items: center;
    .count-item {
      margin-right: 30px;
    }
  }
  .table-expand-form {
    font-size: 0;
  }
  .table-expand-form label {
    width: 90px;
    color: #99a9bf;
  }
  .table-expand-form .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
  .showactions {
    opacity: 1;
  }
  .namerow {
    .namezh {
      color: #000;
    }
    .rowactions {
      float: right;
      opacity: 0;
      cursor: pointer;
      color: #1e51db;
      .brush {
        color: #c04546;
        transform: rotate(-135deg);
        margin-left: 10px;
      }
    }
    &:hover {
      .rowactions {
        @extend .showactions;
      }
    }
  }
</style>
